import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { ResponseModel } from '../model/comm/response-model';
import { ReportUrls } from './report.urls.conf';
import { Shift } from '../model/report/shift';
declare const $: any;
import * as moment from 'moment';
import { GlobalDataManager } from './global-data-manager';
import * as Enumerable from 'linq';
import { TVResource } from '../model/comm/tv-resource';
import { SubArea } from '../model/report/sub-area';
import { LocalStorage } from '../localstorage/local.storage';
import { Router } from '@angular/router';
import { ReplaySubject } from 'rxjs';
// 监控类型与监控描述
const monitorTypeList = [
    { 'type': 'V_LOAD_LAST_HOUR', 'description': '上一小时产量-上线' },
    { 'type': 'V_UNLD_LAST_HOUR', 'description': '上一小时产量-下线' },
    { 'type': 'V_LOAD_CURR_HOUR', 'description': '当前小时产量-上线' },
    { 'type': 'V_UNLD_CURR_HOUR', 'description': '当前小时产量-下线' },
    { 'type': 'V_LOAD_CURR', 'description': '累计产量-上线' },
    { 'type': 'V_UNLD_CURR', 'description': '累计产量-下线' },
    { 'type': 'D_FLT', 'description': '1=报警，0=正常' },
    { 'type': 'D_FLT_ACK', 'description': '1=报警响应，0=正常' },
    { 'type': 'D_GD', 'description': '产量（整型）' },
    { 'type': 'D_AUTO_CYC', 'description': '1=运行，0=非自动' },
    { 'type': 'D_BYPASS', 'description': '1=旁路、其他，0=非旁路' },
    { 'type': 'D_MAN_MODE', 'description': '1=手动，0=非手动' },
    { 'type': 'V_NO_COMM', 'description': '1=中断，0=正常' },
    { 'type': 'D_BLK', 'description': '1=堵料，0=正常' },
    { 'type': 'D_STRV', 'description': '1=待料，0=正常' },
    { 'type': 'V_TARG_CNT', 'description': '目标产量（整型）' },
    { 'type': 'V_TARG_CNT_ALL', 'description': '计划产量（整型）' },
    { 'type': 'V_BOTTLENECK', 'description': '1=瓶颈工位，0=非瓶颈工位' },
    { 'type': 'V_CURR_SHIFT', 'description': '当前班次' },
    { 'type': 'V_CURR_HOUR', 'description': '当前第几小时' },
    { 'type': 'V_PRODDATE', 'description': '当前生产日期' },
    { 'type': 'V_NUM_OPS_DOWN', 'description': '未在线设备数量' },
    { 'type': 'V_AVG_CT', 'description': '节拍（单位：秒）' },
    { 'type': 'V_PART_TYPE_DESC', 'description': '型号（字符串）' },
    { 'type': 'D_PALLET', 'description': '托盘数（整型）' },
    { 'type': 'D_TRACK_ID1', 'description': '追溯信息（字符串）' },
    {
        'type': 'V_TOT_DT_DA_S1',
        'description': '第1班停机时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_DT_DA_S2',
        'description': '第2班停机时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_DT_DA_S3',
        'description': '第3班停机时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_BT_DA_S1',
        'description': '第1班堵料时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_BT_DA_S2',
        'description': '第2班堵料时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_BT_DA_S3',
        'description': '第3班堵料时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_ST_DA_S1',
        'description': '第1班待料时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_ST_DA_S2',
        'description': '第2班待料时间（单位：秒）显示为分钟'
    },
    {
        'type': 'V_TOT_ST_DA_S3',
        'description': '第3班待料时间（单位：秒）显示为分钟'
    },
    { 'type': 'V_NUM_DOWN_DA_S1', 'description': '第1班停机次数·' },
    { 'type': 'V_NUM_DOWN_DA_S2', 'description': '第2班停机次数' },
    { 'type': 'V_NUM_DOWN_DA_S3', 'description': '第3班停机次数' },
    { 'type': 'V_NUM_BLK_DA_S1', 'description': '第1班堵料次数' },
    { 'type': 'V_NUM_BLK_DA_S2', 'description': '第2班堵料次数' },
    { 'type': 'V_NUM_BLK_DA_S3', 'description': '第3班堵料次数' },
    { 'type': 'V_NUM_STRV_DA_S1', 'description': '第1班待料次数' },
    { 'type': 'V_NUM_STRV_DA_S2', 'description': '第2班待料次数' },
    { 'type': 'V_NUM_STRV_DA_S3', 'description': '第3班待料次数' }
];
/**
 * 通用的服务
 * 包含了一些通用的方法
 */
@Injectable()
export class CommService {
    本地测试
    // CSSUrl = 'http://localhost:8080/report';

    //198服务器各后端地址
    // LGEUrl = 'http://10.9.128.198:9092/report';
    // GF6Url = 'http://10.9.128.198:8080/report';
    // CSSUrl = 'http://10.9.128.198:9093/report';
    // CSS5Url = 'http://10.9.128.198:9096/report';
    // GF9Url = 'http://10.9.128.198:9091/report';
    // BEV3Url = 'http://10.9.128.198:8082/report';
    // B121Url = 'http://10.9.128.198:9097/report';
    // K226Url = 'http://10.9.128.198:8081/report';

    //60服务器各后端地址
    LGEUrl = 'http://10.19.9.63:8080/report';
    GF6Url = 'http://10.19.9.63:8081/report';

    CSSUrl = 'http://10.19.9.64:8080/report';
    CSS5Url = 'http://10.19.9.64:8081/report';

    GF9Url = 'http://10.19.9.74:8080/report';
    BEV3Url = 'http://10.19.9.74:8081/report';
    B121Url = 'http://10.19.9.74:8082/report';
    K226Url = 'http://10.19.9.74:8083/report';
    
    GFEUrl = 'http://10.19.9.75:8080/report';
    HEVUrl = 'http://10.19.9.75:8081/report';

    UBEVUrl = 'http://10.19.14.6:8080/report';
    PHEVUrl = 'http://10.19.14.10:8080/report';

    selectedShop = 'NCXB';
    lodingShopSelectedData = true;

    emitter :ReplaySubject<any> = new ReplaySubject();

    emitterShop :ReplaySubject<any> = new ReplaySubject();

    onSubAreaChanged(data){
        this.emitter.next(data);
    }

    onShopSelectedChanged(data){
        this.emitterShop.next(data);
    }

    public shifts: Array<{ shiftId: string, shiftName: string }> = [
        { shiftId: '-1', shiftName: '全部' },
        { shiftId: '1', shiftName: '早班' },
        { shiftId: '2', shiftName: '中班' },
        { shiftId: '3', shiftName: '晚班' },
    ];

    public toolAttachmentTypes: Array<{ typeId: string, typeName: string }> = [
        { typeId: '', typeName: '全部' },
        { typeId: 'TD', typeName: '刀具图纸' },
        { typeId: 'TL', typeName: '刀具布局图' },
    ];
    public booleanSelectItems: Array<{ value: number, text: string }> = [
        { value: 0, text: '否' },
        { value: 1, text: '是' },
    ];
    constructor(protected http: Http, private ls: LocalStorage, private router: Router, protected httpClient: HttpClient) {
    }

    getToken() {
        return this.ls.get('ptpmc_token');
    }

    getConfig(url) {
        return this.http.get(url);
    }
    /**
     * HttpClient
     */

    exporttable2Excel(id) {
        $('#' + id).table2excel({
            filename: 'export'
        });
    }

    get(url): Observable<any> {
        return this.httpClient.get(url).catch(error => {
            this.showNotification('数据请求失败:' + error.message, 'danger');
            return Observable.of({ description: error.message });
        });
    }
    getOnHeader(url, options): Observable<any> {
        return this.httpClient.get(url, options).catch(error => {
            this.showNotification('数据请求失败:' + error.message, 'danger');
            return Observable.of({ description: error.message });
        });
    }
    post(url, body): Observable<any> {
        return this.httpClient.post(url, body).catch(error => {
            this.showNotification('数据请求失败:' + error.message, 'danger');
            return Observable.of({ description: error.message });
        });
    }
    postOnHeader(url, body, options): Observable<any> {
        return this.httpClient.post(url, body, options).catch(error => {
            this.showNotification('数据请求失败:' + error.message, 'danger');
            return Observable.of({ description: error.message });
        });
    }

    doGet(url: string): Observable<any> {
        return this.get(ReportUrls.BaseUrl + url);
    }

    doGetUrl(url: string): Observable<any> {
        return this.get(url);
    }

    /**
     * 后台获取集合数据
     * */
    doPost(url: string, body: any): Observable<any> {
        const headers = new Headers({ 'Content-Type': 'application/json', 'access-token': this.ls.get('ptpmc_token') });
        const options = new RequestOptions({
            headers: headers
        });
        return this.http.post(ReportUrls.BaseUrl + url, body, options).catch(e => this.handleErrorObservable(e)).map(response => {
            const model: ResponseModel = JSON.parse(response._body);
            return model;
        });
        // return this.post(ReportUrls.BaseUrl + url, JSON.stringify(queryModel));
    }

    getList(queryModel: any, url: string): Observable<any> {
        return this.doPost(url, queryModel);
    }

    /**
     * 更新数据
     * */
    update(updateList: any, url: String): Observable<any> {
        return this.post(ReportUrls.BaseUrl + url, JSON.stringify(updateList));
    }
    /**
     * 更新数据
     * */
    delete(deleteList: any, url: String): Observable<any> {
        return this.post(ReportUrls.BaseUrl + url, JSON.stringify(deleteList));
    }
    /**
     * 根据产线取得工位
     * */
    getTVResourceBySubArea(subAreaCode: String): TVResource[] {
        return Enumerable.from(GlobalDataManager.getTVResources()).where(u => u.subArea === subAreaCode).toArray();
    }
    /**
     * 根据产线取瓶颈设备
     * */
    getSlowestResourceBySubArea(subAreaCode: String): TVResource[] {
        return Enumerable.from(GlobalDataManager.getTVResources())
            .where(u => u.subArea === subAreaCode && u.slowestOP === 1).toArray();
    }
    /**
     * 根据产线取andon分析工位
     * */
     getandonResourceBySubArea(subAreaCode: String): TVResource[] {
        return Enumerable.from(GlobalDataManager.getTVResources())
            .where(u => u.subArea === subAreaCode && u.andonAnalyse === 1).toArray();
    }
    /**
     * 根据产线取SPC设备
     * */
    // getSPCResourceBySubArea(subAreaCode: String): TVResource[] {
    //     return Enumerable.from(GlobalDataManager.getSPCResources())
    //         .where(u => u.subArea === subAreaCode && u.isSPC === 1).toArray();
    // }
    getSubAreas(): SubArea[] {
        return GlobalDataManager.getSubAreas();
    }

    get subAreaList () {
        return GlobalDataManager.getSubAreas();
    }

    getCurrentProject(): any {
        return GlobalDataManager.getProjectSelected();
    }
    getShifts(): any {
        const shiftItems: any = new Array();
        const shift0 = new Shift();
        shift0.shiftId = -1;
        shift0.shiftName = '全部';
        const shift1 = new Shift();
        shift1.shiftId = 1;
        shift1.shiftName = '早班';
        const shift2 = new Shift();
        shift2.shiftId = 2;
        shift2.shiftName = '中班';
        const shift3 = new Shift();
        shift3.shiftId = 3;
        shift3.shiftName = '晚班';
        shiftItems.push(shift1);
        shiftItems.push(shift2);
        shiftItems.push(shift3);
    }

    changeShop(shopName){
        this.selectedShop = shopName;
        this.emitterShop.next(shopName);
        ReportUrls.BaseUrl = Enumerable.from(GlobalDataManager.getProjects())
            .where(u => u.projectName === shopName).first().apiUrl;
        this.initCommResource();
        GlobalDataManager.projectSelected = Enumerable.from(GlobalDataManager.getProjects())
            .where(u => u.projectName === shopName).first();
    }

    initCommResource() {
        this.getList(null, ReportUrls.TVResourceUrl).subscribe(model => {
            if (model.resultCode === 200) {
                GlobalDataManager.setTVResources(model.data);

                this.getList(new SubArea(), ReportUrls.SubAreaUrl).subscribe(e => {
                    if (e.resultCode === 200) {
                        GlobalDataManager.setSubAreas(e.data);
                        this.onSubAreaChanged(e.data)
                        this.router.navigate(['ptpmc', 'home']);

                    } else {
                        alert('初始化区域失败...');
                    }
                });

            } else {
                alert('初始化工位失败...');
            }
        });
        // this.getList(null, ReportUrls.SPCResourceUrl).subscribe(model => {
        //     if (model.resultCode === 200) {
        //         GlobalDataManager.setSPCResources(model.data);

        //         this.getList(new SubArea(), ReportUrls.SubAreaUrl).subscribe(e => {
        //             if (e.resultCode === 200) {
        //                 GlobalDataManager.setSubAreas(e.data);

        //                 this.router.navigate(['ptpmc', 'home']);

        //             } else {
        //                 alert('初始化区域失败...');
        //             }
        //         });

        //     } else {
        //         alert('初始化工位失败...');
        //     }
        // });
    }

    /**
    * @param object 对于在一个页面需要多个DateTimeRange组件
    */
    initDatePicker(object: any, format: string): void {
        // let wkStr = '选择周数:<select  id='wks' onchange='$(\'#DateTimeRange\').val(this.options[this.options.selectedIndex].value)'>';
        // for (let i = 1; i <= 53; i++) {
        //     const wn = moment().week(i);
        //     const s = wn.add('days', -1).format('YYYY-MM-DD HH:mm:ss');
        //     const e = wn.add('days', 6).format('YYYY-MM-DD HH:mm:ss');
        //     wkStr += '<option value =\'' + s + ' - ' + e + '\'>' + '第' + i + '周' + '</option>';
        // }
        // wkStr += '</select>';

        const a = {
            timePicker: true,
            timePicker24Hour: true,
            timePickerIncrement: 10,
            timePickerSeconds: false,
            showWeekNumbers: true,
            singleDatePicker: false,
            showDropdowns: true,
            locale: {
                format: format,
                applyLabel: '应用',
                cancelLabel: '取消',
                customRangeLabel: '自定义',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                weekLabel: '周数',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'],
            },
            applyClass: 'btn-sm btn-success',
            cancelClass: 'btn-sm btn-default',
            ranges: {
                '今日': [moment().startOf('day'), moment()],
                // '昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                '当周': [moment().startOf('week'), moment()],
                // '上周': [moment().subtract(1, 'weeks').startOf('week'), moment().subtract(1, 'weeks').endOf('week')],
                '当月': [moment().startOf('month'), moment()],
                '当年': [moment().startOf('year'), moment()]
            },
            startDate: moment().startOf('month'),
            endDate: moment()
        };
        // a.ranges[wkStr] = [moment().startOf('day'), moment()];
        object.daterangepicker(
            a,
            function (start: any, end: any) {
                object.find('span').html(start.format(format) + ' - ' + end.format(format));
            });
    }

    initDatePicker2(object: any, format: string, single): void {
        const a = {
            timePicker: true,
            timePicker24Hour: true,
            timePickerIncrement: 10,
            timePickerSeconds: false,
            showWeekNumbers: true,
            singleDatePicker: single,
            showDropdowns: true,
            firstDayOfWeek: 1,
            locale: {
                format: format,
                applyLabel: '应用',
                cancelLabel: '取消',
                customRangeLabel: '自定义',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                weekLabel: '周数',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'],
            },
            applyClass: 'btn-sm btn-success',
            cancelClass: 'btn-sm btn-default',
            ranges: {
                '今日': [moment().startOf('day'), moment()],
                '当周': [moment().startOf('week'), moment()],
                '当月': [moment().startOf('month'), moment()],
                '当年': [moment().startOf('year'), moment()]
            },
            startDate: moment().startOf('month'),
            endDate: moment()
        };
        object.daterangepicker(
            a,
            function (start: any, end: any) {
                object.find('span').html(start.format(format) + ' - ' + end.format(format));
            });
    }

    initDatePicker3(object: any, format: string): void {
        const a = {
            timePicker: true,
            timePicker24Hour: true,
            timePickerIncrement: 10,
            timePickerSeconds: false,
            showWeekNumbers: true,
            singleDatePicker: false,
            showDropdowns: true,
            firstDayOfWeek: 1,
            maxDate:moment().subtract('day',1).startOf('day'),
            locale: {
                format: format,
                applyLabel: '应用',
                cancelLabel: '取消',
                customRangeLabel: '自定义',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                weekLabel: '周数',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'],
            },
            applyClass: 'btn-sm btn-success',
            cancelClass: 'btn-sm btn-default',
            ranges: {
                '今日': [moment().startOf('day'), moment()],
                '当周': [moment().startOf('week'), moment()],
                '当月': [moment().startOf('month'), moment()],
                '当年': [moment().startOf('year'), moment()]
            },
            startDate: moment().startOf('month'),
            endDate: moment()
        };
        object.daterangepicker(
            a,
            function (start: any, end: any) {
                object.find('span').html(start.format(format) + ' - ' + end.format(format));
            });
    }

    /**
     * 异常捕获
     * @param error exception catch
     */
    private handleErrorObservable(error: Response | any) {
        console.error(error);
        this.showNotification('数据请求失败:' + error, 'danger');
        return Observable.throw(error);
    }

    /**
     * 
     * @param message notifycation
     * @param notiType   'info', 'success', 'warning', 'danger', 'rose', 'primary'
     * @param align 
     */
    showNotification(message: any, notiType: string) {
        if (notiType === undefined) {
            notiType = 'info';
        }
        $.notify({
            icon: 'notifications',
            message: message
        }, {
                type: notiType,
                timer: 1000,
                delay: 1000,
                offset: {
                    y: 150,
                },
                z_index: 9999,
                placement: {
                    from: 'top',
                    align: 'center'
                }
            });
    }

    /**
     * pdf创建及导出到客户端相关服务
     * @param files pdf文件数据
     */
    exportPdf(files: any) {
        const url = ReportUrls.BaseUrl + ReportUrls.ChartsExportUrl;
        this.post(url, JSON.stringify(files))
            .subscribe(model => {
                if (model.resultCode === 200) {
                    window.open(ReportUrls.BaseUrl + ReportUrls.ChartsShowUrl + model.data);
                } else {
                    this.showNotification('生成PDF失败', undefined);
                }
            });
    }
    // 格式化监控数据
    formatMonitorData(monitorList: any[]) {
        const monitorData = {};
        // 当前班次
        const shiftData = monitorList.find(a => a.signalName === 'V_CURR_SHIFT');
        const shift = shiftData ? shiftData.signalValue : '1';
        // 根据设备名称分组
        const groupByList = this.listGroupBy(monitorList, 'equipment');
        // console.log('groupByList', groupByList);
        monitorData['stationList'] = [];
        for (const key in groupByList) {
            if (Object.prototype.hasOwnProperty.call(groupByList, key)) {
                const element = groupByList[key];
                // 产线数据
                if (key === '______') {
                    // 上一小时上线产量
                    const onlinePreHour = element.find(a => a.signalName === 'V_LOAD_LAST_HOUR');
                    monitorData['onlinePreHour'] = onlinePreHour ? onlinePreHour.signalValue : '';
                    // 上一小时下线产量
                    const offlinePreHour = element.find(a => a.signalName === 'V_UNLD_LAST_HOUR');
                    monitorData['offlinePreHour'] = offlinePreHour ? offlinePreHour.signalValue : '';
                    // 当前小时上线产量
                    const onlineCurrentHour = element.find(a => a.signalName === 'V_LOAD_CURR_HOUR');
                    monitorData['onlineCurrentHour'] = onlineCurrentHour ? onlineCurrentHour.signalValue : '';
                    // 当前小时下线产量
                    const offlineCurrentHour = element.find(a => a.signalName === 'V_UNLD_CURR_HOUR');
                    monitorData['offlineCurrentHour'] = offlineCurrentHour ? offlineCurrentHour.signalValue : '';
                    // 累计上线产量
                    const onlineTotal = element.find(a => a.signalName === 'V_LOAD_CURR');
                    monitorData['onlineTotal'] = onlineTotal ? onlineTotal.signalValue : '';
                    // 累计下线产量
                    const offlineTotal = element.find(a => a.signalName === 'V_UNLD_CURR');
                    monitorData['offlineTotal'] = offlineTotal ? offlineTotal.signalValue : '';
                    // 目标产量
                    const targetProduction = element.find(a => a.signalName === 'V_TARG_CNT');
                    monitorData['targetProduction'] = targetProduction ? targetProduction.signalValue : '';
                    // 未在线设备数量
                    const offlineMachine = element.find(a => a.signalName === 'V_NUM_OPS_DOWN');
                    monitorData['offlineMachine'] = offlineMachine ? offlineMachine.signalValue : '';
                } else {
                    // 工位数据
                    const station = {};
                    // 名称
                    station['code'] = key.replace(/_/g, '');
                    // 状态颜色和文本
                    const monitorStatus = this.getStationStatus(element);
                    station['statusColor'] = monitorStatus.color;
                    station['statusText'] = monitorStatus.text;
                    // 产量
                    const production = element.find(a => a.signalName === 'D_GD');
                    station['production'] = production ? production.signalValue : '';
                    // 型号
                    const model = element.find(a => a.signalName === 'V_PART_TYPE_DESC');
                    station['model'] = model ? model.signalValue : '';
                    // 节拍
                    const jph = element.find(a => a.signalName === 'V_AVG_CT');
                    station['jph'] = jph ? jph.signalValue : '';
                    // 追溯信息
                    const review = element.find(a => a.signalName === 'D_TRACK_ID1');
                    station['review'] = review ? review.signalValue : '';
                    // 在线托盘数
                    const palletNum = element.find(a => a.signalName === 'D_PALLET');
                    station['palletNum'] = palletNum ? palletNum.signalValue : '';
                    // 停机时间、堵料时间、待料时间
                    let interruptTime;
                    let blockTime;
                    let waitTime;
                    switch (shift) {
                        case '1':
                            // 班次1统计
                            const shift1InterruptTime = element.find(a => a.signalName === 'V_TOT_DT_DA_S1');
                            const shift1BlockTime = element.find(a => a.signalName === 'V_TOT_BT_DA_S1');
                            const shift1WaitTime = element.find(a => a.signalName === 'V_TOT_ST_DA_S1');
                            interruptTime = shift1InterruptTime ? shift1InterruptTime.signalValue : '';
                            blockTime = shift1BlockTime ? shift1BlockTime.signalValue : '';
                            waitTime = shift1WaitTime ? shift1WaitTime.signalValue : '';
                            break;
                        case '2':
                            // 班次2统计
                            const shift2InterruptTime = element.find(a => a.signalName === 'V_TOT_DT_DA_S2');
                            const shift2BlockTime = element.find(a => a.signalName === 'V_TOT_BT_DA_S2');
                            const shift2WaitTime = element.find(a => a.signalName === 'V_TOT_ST_DA_S2');
                            interruptTime = shift2InterruptTime ? shift2InterruptTime.signalValue : '';
                            blockTime = shift2BlockTime ? shift2BlockTime.signalValue : '';
                            waitTime = shift2WaitTime ? shift2WaitTime.signalValue : '';
                            break;
                        case '3':
                            // 班次3统计
                            const shift3InterruptTime = element.find(a => a.signalName === 'V_TOT_DT_DA_S3');
                            const shift3BlockTime = element.find(a => a.signalName === 'V_TOT_BT_DA_S3');
                            const shift3WaitTime = element.find(a => a.signalName === 'V_TOT_ST_DA_S3');
                            interruptTime = shift3InterruptTime ? shift3InterruptTime.signalValue : '';
                            blockTime = shift3BlockTime ? shift3BlockTime.signalValue : '';
                            waitTime = shift3WaitTime ? shift3WaitTime.signalValue : '';
                            break;
                        default:
                            break;
                    }
                    station['interruptTime'] = interruptTime;
                    station['blockTime'] = blockTime;
                    station['waitTime'] = waitTime;
                    monitorData['stationList'].push(station);
                }
            }
        }
        console.log('monitorData', monitorData);
        return monitorData;

    }
    // 获取工位状态：运行，堵料，待料，手动，报警，其他，中断（优先级从左到右）
    getStationStatus(monitorList: any[]) {
        // 工位运行状态
        const autoStatus = monitorList.find(a => a.signalName === 'D_AUTO_CYC');
        // 工位堵料状态
        const blockStatus = monitorList.find(a => a.signalName === 'D_BLK');
        // 工位待料状态
        const waitStatus = monitorList.find(a => a.signalName === 'D_STRV');
        // 工位手动状态
        const manualStatus = monitorList.find(a => a.signalName === 'D_MAN_MODE');
        // 工位报警状态
        const alarmStatus = monitorList.find(a => a.signalName === 'D_FLT');
        // 工位其他状态
        const otherStatus = monitorList.find(a => a.signalName === 'D_BYPASS');
        // 工位中断状态
        const interruptStatus = monitorList.find(a => a.signalName === 'V_NO_COMM');
        // 判断工位状态
        if (autoStatus && autoStatus.signalValue === '1') {
            return { color: '#05fb0b', text: '运行' };
        } else if (blockStatus && blockStatus.signalValue === '1') {
            return { color: '#577df7', text: '堵料' };
        } else if (waitStatus && waitStatus.signalValue === '1') {
            return { color: '#fcfbfb', text: '待料' };
        } else if (manualStatus && manualStatus.signalValue === '1') {
            return { color: '#e8fc07', text: '手动' };
        } else if (alarmStatus && alarmStatus.signalValue === '1') {
            return { color: '#fd000c', text: '报警' };
        } else if (otherStatus && otherStatus.signalValue === '1') {
            return { color: '#a44c4c', text: '其他' };
        } else if (interruptStatus && interruptStatus.signalValue === '1') {
            return { color: '#000', text: '中断' };
        } else {
            return { color: '', text: '' };
        }
    }
    // 数组根据某字段group by
    listGroupBy(list: any[], code: string) {
        const groupBy = {};
        for (const i of list) {
            if (groupBy.hasOwnProperty(i[code])) {
                groupBy[i[code]].push(i);
            } else {
                groupBy[i[code]] = [i];
            }
        }
        return groupBy;
    }
}

